﻿#region License

// Copyright (c) 2009, Bill O'Neill (william.w.oneill@gmail.com)
// All rights reserved.
// 
// Redistribution and use in source and binary forms, with or without 
// modification, are permitted provided that the following conditions 
// are met:
// 
// 1. Redistributions of source code must retain the above copyright 
// notice, this list of conditions and the following disclaimer.
// 
// 2. Redistributions in binary form must reproduce the above copyright 
// notice, this list of conditions and the following disclaimer in the 
// documentation and/or other materials provided with the distribution.
// 
// 3. Neither the name of Focal Point Technology Solutions, LLC nor 
// the names of its contributors may be used to endorse or promote 
// products derived from this software without specific prior written 
// permission.
// 
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND 
// CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, 
// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR 
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED 
// TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 
// OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE 
// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH 
// DAMAGE.

#endregion

using System;
using System.Collections.Generic;
using System.Threading;
using X10d.Interface;

namespace x10
{
	internal class Program
	{
		/// <summary>
		/// Shows usage to the user via console standard output
		/// </summary>
		private static void ShowUsage()
		{
			Console.WriteLine("X10 [BETA]");
			Console.WriteLine();
			Console.WriteLine("Sends a command to an X10 device");
			Console.WriteLine("X10 -p comPort -h houseCode -d device -c command");
			Console.WriteLine("  comPort     Specifies the com port where the X10 interface is attached");
			Console.WriteLine("  houseCode   X10 house code, e.g. 'A' for house code A");
			Console.WriteLine("  device      Device number e.g. 'Two' for device 2");
			Console.WriteLine("  command     X10 command, either 'On' or 'Off'");
			Console.WriteLine();
		}

		/// <summary>
		/// Parses the command line arguments
		/// </summary>
		/// <param name="args">
		/// Command line arguments
		/// </param>
		/// <param name="comPort">
		/// Parsed COM port
		/// </param>
		/// <param name="command">
		/// Parsed X10 command
		/// </param>
		/// <returns>
		/// <c>true</c> if the arguments parsed successfully
		/// </returns>
		private static bool TryParse(IEnumerable<string> args, out int comPort, out DeviceCommand command)
		{
			comPort = 0;
			command = null;

			bool parseSuccessful = false;

			DeviceCodeType? deviceCode = null;
			HouseCodeType? houseCode = null;
			FunctionCodeType? functionCode = null;
			int? port = null;

			char? currentSwitch = null;

			try
			{
				foreach (string arg in args)
				{
					if (arg[0] == '-' || arg[0] == '/')
					{
						currentSwitch = arg[1];
					}
					else
					{
						if (currentSwitch.HasValue)
						{
							switch (currentSwitch)
							{
								case 'p':
								case 'P':
									int temp;
									if (int.TryParse(arg, out temp))
									{
										port = temp;
									}

									break;

								case 'h':
								case 'H':
									houseCode = (HouseCodeType) Enum.Parse(typeof (HouseCodeType), arg);
									break;

								case 'd':
								case 'D':
									// TODO: Support numerics instead of strings. 
									// The device code from the user must match the DeviceCodeType enumeration.
									// This is awkward.
									deviceCode = (DeviceCodeType) Enum.Parse(typeof (DeviceCodeType), arg);
									break;

								case 'c':
								case 'C':
									// TODO: Support DIM
									functionCode = (FunctionCodeType) Enum.Parse(typeof (FunctionCodeType), arg);
									break;

								default:
									throw new ArgumentException(
										"Unexpected switch: " + currentSwitch);
							}
						}

						currentSwitch = null;
					}
				}

				if (port.HasValue && houseCode.HasValue && deviceCode.HasValue && functionCode.HasValue)
				{
					comPort = port.Value;

					command = new DeviceCommand { Device = deviceCode.Value, Function = functionCode.Value, HouseCode = houseCode.Value };

					parseSuccessful = true;
				}

			}
			catch
			{
				// Ignore the exception and just return false.
			}

			return parseSuccessful;
		}

		/// <summary>
		/// Simple application that illustrates sending commands to the X10 interface. 
		/// </summary>
		/// <param name="args">
		/// Command line arguments
		/// </param>
		private static void Main(string[] args)
		{
			DeviceCommand command;
			int comPort;

			// This is a quick and dirty hack, but it shows how to use the interface from an application.
			// You can create some Windows batch files to execute various X10 commands and automate
			// them using the Windows scheduler. It's a simple, poorman's approach to home automation.
			if ( TryParse(args, out comPort, out command))
			{
				// Instantiate the class using the COM port...
				CM11AInterface cm11a = new CM11AInterface(comPort);

				// Send one or more commands...
				cm11a.ExecuteCommand( command );

				ManualResetEvent resetEvent = new ManualResetEvent(false);

				// Wait for the command to complete before exiting the program.
				cm11a.CommandComplete += delegate { resetEvent.Set(); };

				if (!resetEvent.WaitOne(5000))
				{
					Console.WriteLine("Timed out waiting for event to complete");
				}
			}
			else
			{
				ShowUsage();
			}

		}
	}
}